//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.baidu.disconf.web.service.config.service.impl;

import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
import com.baidu.disconf.web.config.ApplicationPropertyConfig;
import com.baidu.disconf.web.innerapi.zookeeper.ZooKeeperDriver;
import com.baidu.disconf.web.service.app.bo.App;
import com.baidu.disconf.web.service.app.service.AppMgr;
import com.baidu.disconf.web.service.config.bo.Config;
import com.baidu.disconf.web.service.config.dao.ConfigDao;
import com.baidu.disconf.web.service.config.form.ConfListForm;
import com.baidu.disconf.web.service.config.form.ConfNewItemForm;
import com.baidu.disconf.web.service.config.service.ConfigMgr;
import com.baidu.disconf.web.service.config.vo.ConfListVo;
import com.baidu.disconf.web.service.config.vo.MachineListVo;
import com.baidu.disconf.web.service.env.bo.Env;
import com.baidu.disconf.web.service.env.service.EnvMgr;
import com.baidu.disconf.web.service.zookeeper.config.ZooConfig;
import com.baidu.disconf.web.service.zookeeper.dto.ZkDisconfData;
import com.baidu.disconf.web.service.zookeeper.dto.ZkDisconfData.ZkDisconfDataItem;
import com.baidu.disconf.web.service.zookeeper.service.ZkDeployMgr;
import com.baidu.disconf.web.utils.CodeUtils;
import com.baidu.disconf.web.utils.DiffUtils;
import com.baidu.disconf.web.utils.MyStringUtils;
import com.baidu.dsp.common.constant.DataFormatConstants;
import com.baidu.dsp.common.utils.DataTransfer;
import com.baidu.dsp.common.utils.ServiceUtil;
import com.baidu.dsp.common.utils.email.LogMailBean;
import com.baidu.ub.common.db.DaoPageResult;
import com.github.knightliao.apollo.utils.data.GsonUtils;
import com.github.knightliao.apollo.utils.io.OsUtil;
import com.github.knightliao.apollo.utils.time.DateUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ConfigMgrImpl implements ConfigMgr {
    protected static final Logger LOG = LoggerFactory.getLogger(ConfigMgrImpl.class);
    @Autowired
    private ConfigDao configDao;
    @Autowired
    private AppMgr appMgr;
    @Autowired
    private EnvMgr envMgr;
    @Autowired
    private ZooKeeperDriver zooKeeperDriver;
    @Autowired
    private ZooConfig zooConfig;
    @Autowired
    private ZkDeployMgr zkDeployMgr;
    @Autowired
    private LogMailBean logMailBean;
    @Autowired
    private ApplicationPropertyConfig applicationPropertyConfig;

    public ConfigMgrImpl() {
    }

    public List<String> getVersionListByAppEnv(Long appId, Long envId) {
        ArrayList versionList = new ArrayList();
        List configs = this.configDao.getConfByAppEnv(appId, envId);
        Iterator var6 = configs.iterator();

        while(var6.hasNext()) {
            Config config = (Config)var6.next();
            if(!versionList.contains(config.getVersion())) {
                versionList.add(config.getVersion());
            }
        }

        return versionList;
    }

    public List<File> getDisonfFileList(ConfListForm confListForm) {
        List configList = this.configDao.getConfigList(confListForm.getAppId(), confListForm.getEnvId(), confListForm.getVersion());
        String curTime = DateUtils.format(new Date(), DataFormatConstants.COMMON_TIME_FORMAT);
        curTime = "tmp" + File.separator + curTime;
        OsUtil.makeDirs(curTime);
        ArrayList files = new ArrayList();
        Iterator var6 = configList.iterator();

        while(var6.hasNext()) {
            Config config = (Config)var6.next();
            if(config.getType().equals(Integer.valueOf(DisConfigTypeEnum.FILE.getType()))) {
                File file = new File(curTime, config.getName());

                try {
                    FileUtils.writeByteArrayToFile(file, config.getValue().getBytes());
                } catch (IOException var9) {
                    LOG.warn(var9.toString());
                }

                files.add(file);
            }
        }

        return files;
    }

    public DaoPageResult<ConfListVo> getConfigList(ConfListForm confListForm, final boolean fetchZk, final boolean getErrorMessage) {
        DaoPageResult configList = this.configDao.getConfigList(confListForm.getAppId(), confListForm.getEnvId(), confListForm.getVersion(), confListForm.getPage());
        final App app = this.appMgr.getById(confListForm.getAppId());
        final Env env = this.envMgr.getById(confListForm.getEnvId());

        Map<String, ZkDisconfData> zkDataMapNotFinal = new HashMap();
        if(fetchZk) {
            zkDataMapNotFinal = this.zkDeployMgr.getZkDisconfDataMap(app.getName(), env.getName(), confListForm.getVersion());
        }
        final Map<String, ZkDisconfData> zkDataMap = zkDataMapNotFinal;

        DaoPageResult configListVo = ServiceUtil.getResult(configList, new DataTransfer<Config, ConfListVo>() {
            @Override
            public ConfListVo transfer(Config input) {
                String appNameString = app.getName();
                String envName = env.getName();
                ZkDisconfData zkDisconfData = null;
                if(zkDataMap != null && ((Map)zkDataMap).keySet().contains(input.getName())) {
                    zkDisconfData = (ZkDisconfData)((Map)zkDataMap).get(input.getName());
                }

                ConfListVo configListVo = ConfigMgrImpl.this.convert(input, appNameString, envName, zkDisconfData);
                if(!fetchZk || !getErrorMessage) {
                    configListVo.setValue("");
                    configListVo.setMachineList(new ArrayList());
                }

                return configListVo;
            }
        });
        return configListVo;
    }

    private MachineListVo getZkData(List<ZkDisconfDataItem> datalist, Config config) {
        int errorNum = 0;
        Iterator var5 = datalist.iterator();

        while(var5.hasNext()) {
            ZkDisconfDataItem machineListVo = (ZkDisconfDataItem)var5.next();
            if(config.getType().equals(Integer.valueOf(DisConfigTypeEnum.FILE.getType()))) {
                List errorKeyList = this.compareConfig(machineListVo.getValue(), config.getValue());
                if(errorKeyList.size() != 0) {
                    machineListVo.setErrorList(errorKeyList);
                    ++errorNum;
                }
            } else if(!machineListVo.getValue().trim().equals(config.getValue().trim())) {
                ArrayList var8 = new ArrayList();
                var8.add(config.getValue().trim());
                machineListVo.setErrorList(var8);
                ++errorNum;
            }
        }

        MachineListVo var7 = new MachineListVo();
        var7.setDatalist(datalist);
        var7.setErrorNum(errorNum);
        var7.setMachineSize(datalist.size());
        return var7;
    }

    private ConfListVo convert(Config config, String appNameString, String envName, ZkDisconfData zkDisconfData) {
        ConfListVo confListVo = new ConfListVo();
        confListVo.setConfigId((Long)config.getId());
        confListVo.setAppId(config.getAppId());
        confListVo.setAppName(appNameString);
        confListVo.setEnvName(envName);
        confListVo.setEnvId(config.getEnvId());
        confListVo.setCreateTime(config.getCreateTime());
        confListVo.setModifyTime(config.getUpdateTime().substring(0, 12));
        confListVo.setKey(config.getName());
        confListVo.setValue(CodeUtils.unicodeToUtf8(config.getValue()));
        confListVo.setVersion(config.getVersion());
        confListVo.setType(DisConfigTypeEnum.getByType(config.getType().intValue()).getModelName());
        confListVo.setTypeId(config.getType());
        if(zkDisconfData != null) {
            confListVo.setMachineSize(zkDisconfData.getData().size());
            List datalist = zkDisconfData.getData();
            MachineListVo machineListVo = this.getZkData(datalist, config);
            confListVo.setErrorNum(machineListVo.getErrorNum());
            confListVo.setMachineList(machineListVo.getDatalist());
            confListVo.setMachineSize(machineListVo.getMachineSize());
        }

        return confListVo;
    }

    private List<String> compareConfig(String zkData, String dbData) {
        ArrayList errorKeyList = new ArrayList();
        Properties prop = new Properties();

        try {
            prop.load(IOUtils.toInputStream(dbData));
        } catch (Exception var11) {
            LOG.error(var11.toString());
            errorKeyList.add(zkData);
            return errorKeyList;
        }

        Map zkMap = GsonUtils.parse2Map(zkData);
        Iterator var7 = zkMap.keySet().iterator();

        while(var7.hasNext()) {
            String keyInZk = (String)var7.next();
            Object valueInDb = prop.get(keyInZk);
            String zkDataStr = (String)zkMap.get(keyInZk);

            try {
                if(zkDataStr == null && valueInDb != null || zkDataStr != null && valueInDb == null) {
                    errorKeyList.add(keyInZk);
                } else {
                    boolean e = true;
                    if(MyStringUtils.isDouble(zkDataStr) && MyStringUtils.isDouble(valueInDb.toString())) {
                        if(Math.abs(Double.parseDouble(zkDataStr) - Double.parseDouble(valueInDb.toString())) > 0.001D) {
                            e = false;
                        }
                    } else if(!zkDataStr.equals(valueInDb.toString().trim())) {
                        e = false;
                    }

                    if(!e) {
                        errorKeyList.add(keyInZk + "\t" + DiffUtils.getDiffSimple(zkDataStr, valueInDb.toString().trim()));
                    }
                }
            } catch (Exception var12) {
                LOG.warn(var12.toString() + " ; " + keyInZk + " ; " + (String)zkMap.get(keyInZk) + " ; " + valueInDb);
            }
        }

        return errorKeyList;
    }

    public ConfListVo getConfVo(Long configId) {
        Config config = (Config)this.configDao.get(configId);
        App app = this.appMgr.getById(config.getAppId());
        Env env = this.envMgr.getById(config.getEnvId());
        return this.convert(config, app.getName(), env.getName(), (ZkDisconfData)null);
    }

    public MachineListVo getConfVoWithZk(Long configId) {
        Config config = (Config)this.configDao.get(configId);
        App app = this.appMgr.getById(config.getAppId());
        Env env = this.envMgr.getById(config.getEnvId());
        DisConfigTypeEnum disConfigTypeEnum = DisConfigTypeEnum.FILE;
        if(config.getType().equals(Integer.valueOf(DisConfigTypeEnum.ITEM.getType()))) {
            disConfigTypeEnum = DisConfigTypeEnum.ITEM;
        }

        ZkDisconfData zkDisconfData = this.zkDeployMgr.getZkDisconfData(app.getName(), env.getName(), config.getVersion(), disConfigTypeEnum, config.getName());
        if(zkDisconfData == null) {
            return new MachineListVo();
        } else {
            MachineListVo machineListVo = this.getZkData(zkDisconfData.getData(), config);
            return machineListVo;
        }
    }

    public Config getConfigById(Long configId) {
        return (Config)this.configDao.get(configId);
    }

    @Transactional(
            propagation = Propagation.REQUIRED,
            rollbackFor = {RuntimeException.class}
    )
    public String updateItemValue(Long configId, String value) {
        Config config = this.getConfigById(configId);
        String oldValue = config.getValue();
        this.configDao.updateValue(configId, CodeUtils.utf8ToUnicode(value));
        String toEmails = this.appMgr.getEmails(config.getAppId());
        if(this.applicationPropertyConfig.isEmailMonitorOn()) {
            boolean isSendSuccess = this.logMailBean.sendHtmlEmail(toEmails, " config update", DiffUtils.getDiff(CodeUtils.unicodeToUtf8(oldValue), value, config.toString(), this.getConfigUrlHtml(config)));
            return isSendSuccess?"修改成功，邮件通知成功":"修改成功，邮件发送失败，请检查邮箱配置";
        } else {
            return "修改成功";
        }
    }

    private String getConfigUrlHtml(Config config) {
        return "<br/>点击<a href=\'http://" + this.applicationPropertyConfig.getDomain() + "/modifyFile.html?configId=" + config.getId() + "\'> 这里 </a> 进入查看<br/>";
    }

    private String getNewValue(String newValue, String identify, String htmlClick) {
        String contentString = StringEscapeUtils.escapeHtml(identify) + "<br/>" + htmlClick + "<br/><br/> ";
        String data = "<br/><br/><br/><span style=\'color:#FF0000\'>New value:</span><br/>";
        contentString = contentString + data + StringEscapeUtils.escapeHtml(newValue);
        return contentString;
    }

    public void notifyZookeeper(Long configId) {
        ConfListVo confListVo = this.getConfVo(configId);
        if(confListVo.getTypeId().equals(Integer.valueOf(DisConfigTypeEnum.FILE.getType()))) {
            this.zooKeeperDriver.notifyNodeUpdate(confListVo.getAppName(), confListVo.getEnvName(), confListVo.getVersion(), confListVo.getKey(), GsonUtils.toJson(confListVo.getValue()), DisConfigTypeEnum.FILE);
        } else {
            this.zooKeeperDriver.notifyNodeUpdate(confListVo.getAppName(), confListVo.getEnvName(), confListVo.getVersion(), confListVo.getKey(), confListVo.getValue(), DisConfigTypeEnum.ITEM);
        }

    }

    public String getValue(Long configId) {
        return this.configDao.getValue(configId);
    }

    public void newConfig(ConfNewItemForm confNewForm, DisConfigTypeEnum disConfigTypeEnum) {
        Config config = new Config();
        config.setAppId(confNewForm.getAppId());
        config.setEnvId(confNewForm.getEnvId());
        config.setName(confNewForm.getKey());
        config.setType(Integer.valueOf(disConfigTypeEnum.getType()));
        config.setVersion(confNewForm.getVersion());
        config.setValue(CodeUtils.utf8ToUnicode(confNewForm.getValue()));
        String curTime = DateUtils.format(new Date(), DataFormatConstants.COMMON_TIME_FORMAT);
        config.setCreateTime(curTime);
        config.setUpdateTime(curTime);
        this.configDao.create(config);
        String toEmails = this.appMgr.getEmails(config.getAppId());
        if(this.applicationPropertyConfig.isEmailMonitorOn()) {
            this.logMailBean.sendHtmlEmail(toEmails, " config new", this.getNewValue(confNewForm.getValue(), config.toString(), this.getConfigUrlHtml(config)));
        }

    }

    public void delete(Long configId) {
        this.configDao.delete(configId);
    }
}
